"""
用户模块序列化器
"""
from rest_framework import serializers
from django.contrib.auth.models import User
from .models import UserProfile


class UserProfileSerializer(serializers.ModelSerializer):
    """用户扩展信息序列化器"""
    supervisor_name = serializers.CharField(source='supervisor.username', read_only=True)
    
    class Meta:
        model = UserProfile
        fields = [
            'id', 'student_id', 'major', 'class_name', 'gender',
            'phone', 'department', 'position', 'employee_id',
            'hire_date', 'supervisor', 'supervisor_name', 'remarks',
            'cet4_score', 'cet4_status', 'cet4_exemption_pic', 'cet4_score_pic', 'cet4_reject_reason',
            'cet6_score', 'cet6_status', 'cet6_exemption_pic', 'cet6_score_pic', 'cet6_reject_reason',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']


class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    profile = UserProfileSerializer(required=False)
    
    class Meta:
        model = User
        fields = [
            'id', 'username', 'email', 'first_name', 'last_name',
            'profile', 'is_active', 'is_staff', 'date_joined'
        ]
        read_only_fields = ['id', 'date_joined']
    
    def create(self, validated_data):
        """创建用户及其扩展信息"""
        profile_data = validated_data.pop('profile', {})
        password = validated_data.pop('password', None)
        
        # 创建用户
        user = User.objects.create(**validated_data)
        if password:
            user.set_password(password)
            user.save()
        
        # 创建或更新扩展信息
        UserProfile.objects.create(user=user, **profile_data)
        
        return user
    
    def update(self, instance, validated_data):
        """更新用户及其扩展信息"""
        profile_data = validated_data.pop('profile', None)
        password = validated_data.pop('password', None)
        
        # 更新用户基本信息
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        
        if password:
            instance.set_password(password)
        
        instance.save()
        
        # 更新扩展信息
        if profile_data is not None:
            profile, created = UserProfile.objects.get_or_create(user=instance)
            for attr, value in profile_data.items():
                setattr(profile, attr, value)
            profile.save()
        
        return instance


class LoginSerializer(serializers.Serializer):
    """登录序列化器"""
    username = serializers.CharField(required=True, help_text='用户名')
    password = serializers.CharField(required=True, write_only=True, help_text='密码')


class UserDetailSerializer(serializers.ModelSerializer):
    """用户详情序列化器（包含更多信息）"""
    profile = UserProfileSerializer(read_only=True)
    role = serializers.SerializerMethodField()
    
    class Meta:
        model = User
        fields = [
            'id', 'username', 'email', 'first_name', 'last_name',
            'profile', 'role', 'is_active', 'is_staff', 'is_superuser',
            'last_login', 'date_joined'
        ]
    
    def get_role(self, obj):
        """获取用户角色"""
        if obj.is_superuser:
            return 'admin'
        elif obj.is_staff:
            return 'office'
        elif hasattr(obj, 'profile'):
            # 根据职位判断角色
            position = obj.profile.position
            if '辅导员' in position:
                return 'counselor'
            elif '班委' in position:
                return 'monitor'
        return 'student'
